import {
  Controller,
  Get,
  Query,
  Post,
  Body,
  Delete,
  Param,
  Put,
} from '@nestjs/common'
import { Types } from 'mongoose'
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger'
import { UserModel, UserClass, UpdateUserDto, bulkDelDto } from './user.model'
import type { IResposeBase, IResPaginated } from '../common/response'

enum SelectVal {
  name = 'name',
  username = 'username',
}

function getSelectVal(key: SelectVal, val = '') {
  switch (key) {
    case SelectVal.name:
      return { name: { $regex: val, $options: 'i' } }
    case SelectVal.username:
      return { username: { $regex: val, $options: 'i' } }
    default:
      //穷尽性检查
      const _exhaust: never = key
      return _exhaust
  }
}

@ApiBearerAuth()
@Controller('admin/acl/user')
@ApiTags('用户权限管理')
export class UserController {
  @Get('/paginate')
  @ApiOperation({
    summary: '获取分页用户列表',
  })
  async getPaginatedUsers(
    @Query('page') page = 1,
    @Query('limit') limit = 10,
    @Query('key') key = SelectVal.name,
    @Query('val') val = '',
  ): Promise<IResPaginated<UserClass> | null> {
    const totalCount = await UserModel.countDocuments(getSelectVal(key, val))
    const users = await UserModel.find(getSelectVal(key, val))
      .select('-__v')
      .sort({ _id: -1 })
      .skip((Number(page) - 1) * Number(limit))
      .limit(Number(limit))
      .exec()
    return {
      data: users,
      meta: {
        currentPage: Number(page),
        itemPerPage: Number(limit),
        totalItems: totalCount,
        totalPages: Math.ceil(totalCount / Number(limit)),
      },
    }
  }

  @Get(':id')
  @ApiOperation({ summary: '获取用户详情' })
  async getUserById(@Param('id') id: Types.ObjectId): Promise<UserClass> {
    return await UserModel.findById(id).exec()
  }

  // @Get('/query')
  // @ApiOperation({ summary: '根据用户名获取用户详情' })
  // async getUserByUserName(@Query('username') username: string) {
  //   const res = await this.getPaginatedUsers(
  //     1,
  //     10,
  //     SelectVal.username,
  //     username,
  //   )
  //   if (res && res.data.length > 0) {
  //     return res.data[0]
  //   }
  // }

  @Post()
  @ApiOperation({ summary: '创建用户' })
  async createUser(@Body() userData: UpdateUserDto): Promise<IResposeBase> {
    await UserModel.create(userData)
    return {
      success: true,
      message: '创建用户成功！',
    }
  }

  @Put(':id')
  @ApiOperation({ summary: '更新用户' })
  async updateUser(
    @Param('id') id: Types.ObjectId,
    @Body() userUpDateData: UpdateUserDto,
  ): Promise<IResposeBase> {
    await UserModel.findByIdAndUpdate(id, userUpDateData, {
      runValidators: true,
      new: true, //提供应用更新后的对象
    }).exec()
    return {
      success: true,
      message: '更新用户成功！',
    }
  }

  @Delete(':id')
  @ApiOperation({ summary: '删除用户' })
  async deleteUser(@Param('id') id: Types.ObjectId): Promise<IResposeBase> {
    await UserModel.findByIdAndDelete(id).exec()
    return {
      success: true,
      message: '删除用户成功！',
    }
  }

  @Post('/bulkDelete')
  @ApiOperation({ summary: '批量删除用户' })
  async bulkDelete(@Body() body: bulkDelDto): Promise<IResposeBase> {
    try {
      await UserModel.deleteMany({ _id: { $in: body } }).exec()
      return {
        success: true,
        message: '批量删除用户成功！',
      }
    } catch (error) {
      return {
        success: false,
        message: `批量删除用户失败！${error}`,
      }
    }
  }
}
